<!--闪信模板管理-->
<template>
  <div class="instantSms">
    <affix :label="$t('configLazyLoad.sms.quickSmsTemplate')"></affix>
    <div class="prompt">
      温馨提示：目前闪信报备需要线下提交资料审核，闪信报备需提供资料：闪信内容、模版签名、营业执照、签名授权书。如需开通闪信请直接联系对接人或致电客服4001-113-114。
    <!--<div class="bao-bei">-->
      <!--<el-button type="primary" class="primary_btn" @click.stop="smsTempEditShow">{{$t('configLazyLoad.sms.ReportFlashTemplate')}}</el-button>-->
    </div>
    <!--报备 闪信模板 start========================================================-->
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" class="edit-sms-temp-wrap" :title="$t('configLazyLoad.sms.editFlashTemplate')" :visible.sync="isSmsTempEditShow" width="50%" @close="editTempDialogClose">
      <div class="edit-sms-temp">
          <div class="edit-sms-temp-left">
            <el-form :model="ruleFormBaoBei" ref="ruleFormBaoBei" class="demo-ruleForm">
            <div class="edit-sms-temp-line">
              <span class="title-temp">{{$t('sms.tempTitle')}}</span>
              <input type="text" class="title-inp" v-model.trim="ruleFormBaoBei.name" :placeholder="$t('sms.pleaseInpTitle')">
            </div>
            <div class="edit-sms-temp-line">
              <span class="title-temp line-height-x">{{$t('sms.tempCon')}}</span>
              <textarea class="content-inp" name="content" v-model.trim="ruleFormBaoBei.content" @keyup="editTempChange" :placeholder="$t('public.pleaseEnter')"></textarea>
            </div>
            <div class="edit-sms-temp-line">
              <div class="edit-sms-temp-line-tip">
                {{$t('configLazyLoad.sms.example1')}}<br/>
                <span class="span-color">{{$t('configLazyLoad.sms.example2')}}</span><br/>
                {{$t('configLazyLoad.sms.example3')}}<br/>
                {{$t('configLazyLoad.sms.example4')}}
              </div>
            </div>
            <div class="edit-sms-temp-line">
              <span class="title-temp">{{$t('sms.tempSign')}}</span>
              [<input type="text" name="sign" class="sign-inp" v-model.trim="ruleFormBaoBei.sign" @keyup="editTempChange($event)" :placeholder="$t('sms.pleaseInpSign')">]
            </div>
            <div class="edit-sms-temp-line">
              <div style="color: #737373;" v-if="isShowTextCount" v-html="$t('sms.reciprocalNum', {difference : difference, textCount : textCount})"></div>
              <!--<div style="color: #4c4c4c;" v-if="splitCount > 1 && isShowTextCount" v-html="$t('sms.smsPagingNum', {splitCount : splitCount})"></div>-->
            </div>
            <!--<div class="edit-sms-temp-line">-->
              <!--<p class="title-temp">模板通道</p>-->
              <!--<el-select v-model="ruleFormBaoBei.channel" placeholder="请选择">-->
                <!--<el-option-->
                  <!--v-for="item in flashSmsChannels"-->
                  <!--:label="item.codeName"-->
                  <!--:value="item.codeValue">-->
                <!--</el-option>-->
              <!--</el-select>-->
            <!--</div>-->
            <div class="edit-sms-temp-line">
              <el-button type="primary" class="edit-sms-temp-submit primary_btn" @click.stop="postSmsTemplate">{{$t('sms.smsTempSubmit')}}</el-button>
            </div>
            </el-form>
          </div>
        <div class="edit-sms-temp-right">
          <div class="show_sms_tmpl_box">
            <p class="top">{{$t('configLazyLoad.sms.flashLetter')}}</p>
            <div class="center">
              <span v-if="ruleFormBaoBei.sign">[</span>
              <span v-if="ruleFormBaoBei.sign">{{ruleFormBaoBei.sign}}</span>
              <span v-if="ruleFormBaoBei.sign">]</span>&nbsp;&nbsp;
              <span>{{ruleFormBaoBei.content}}</span>
            </div>
            <p class="bottom">{{$t('public.close')}}</p>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click.stop="closeSmsTempEdit">{{$t('sms.smsTempClose')}}</el-button>
      </div>
    </el-dialog>
    <!--报备 闪信模板 end========================================================-->
    <div class="tables">
      <div class="deploy">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="currentPage"
          :count="count"
          :pageSize="limit"
          @turnPage="handleCurrentChange"
          :totalPage="Math.ceil(count/limit)"
        >
        </Pagination>
      </div>
      <!-- 搜索结果  表格 start========================================================-->
      <el-table :data="tableData" stripe style="width: 100%" size="mini" border>
        <el-table-column prop="_id" :label="$t('configLazyLoad.sms.number')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="name" :label="$t('sms.tempTitle')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="num" :label="$t('configLazyLoad.sms.templateNumber')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="content" :label="$t('configLazyLoad.sms.templateContent')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="signCon" :label="$t('sms.tempSign')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="statusName" :label="$t('sms.smsState')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="lastUpdateTime" :label="$t('configLazyLoad.sms.lastUpdateTime')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column  :label="$t('sms.operate')" width="60">
          <template scope="scope">
            <a style="margin-right: 10px;" @click.stop="showSmsTempDetail(scope.$index, tableData)">{{$t('sms.searchToLook')}}</a>
            <!--<a style="margin-right: 10px;" @click.stop="smsTempEditShowFromTable(scope.$index, tableData)">{{$t('public.edit')}}</a>-->
            <!--<a v-if="tableData[scope.$index].status === 'pass'" class="red" style="margin-right: 10px;" @click.stop="stopUseSmsTemplateToCheck(scope.$index, tableData)">{{$t('sms.stop')}}</a>-->
            <!--<a v-if="tableData[scope.$index].status === 'stop'" style="margin-right: 10px;"  @click.stop="reUseSmsTemplateToCheck(scope.$index, tableData)">{{$t('sms.reuse')}}</a>-->
            <!--<a class="red" v-if="tableData[scope.$index].status === 'back'" @click.stop="delSmsTempFromTable(scope.$index, tableData)">{{$t('sms.del')}}</a>-->
          </template>
        </el-table-column>
      </el-table>
      <!-- 搜索结果  表格 end========================================================-->
      <!-- 查看  表格内 详细信息 start========================================================-->
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" class="sms-temp-detail-wrap" :title="$t('configLazyLoad.sms.viewTemplate')" :visible.sync="isShowSmsTempDetail" width="50%" @close="showSmsTempDetailDialogClose">
        <div class="sms-temp-detail-con-wrap">
          <div class="sms-temp-detail-top">
            <el-row>
              <el-col :span="3"><div>{{$t('sms.tempTitle')}}：</div></el-col>
              <el-col :span="21">{{smsTempDetail.name}}</el-col>
            </el-row>
            <el-row>
              <el-col :span="3"><div>{{$t('configLazyLoad.sms.flashLetterContent')}}：</div></el-col>
              <el-col :span="21"><div class="sms-detail-con">{{smsTempDetail.content}}</div></el-col>
            </el-row>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="primary_btn" @click.stop="closeShowSmsTempDetail">{{$t('sms.smsTempClose')}}</el-button>
        </div>
      </el-dialog>
      <!-- 查看  表格内 详细信息 end========================================================-->
    </div>
  </div>
</template>
<script>
  import affix from '../../../../../ui-modules/affix/Affix.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  export default {
    name: 'instantSms',
    data () {
      return {
        shanSigns: [],   //   闪信 签名
        flashSmsStatuss: [],   //  闪信 状态
        tableData: [],
        currentPage: 1,
        limit: 10,
        count: 0,
//        整个页面的 v-if锁
//        isShowSmsTemplate: false,
//        报备闪信模板状态
        isSmsTempEditShow: false,
//        查看dialog状态
        isShowSmsTempDetail: false,
//        查看dialog中  添加回复按钮状态
        isShowAddAnswerState: false,
//        编辑闪信模板 计数显隐
        isShowTextCount: false,
//        报备闪信模板内容
        ruleFormBaoBei: {
          account: '',
          name: '',
          content: '',
          sign: '',
          _id: ''
        },
        textCount: 48,
        difference: 46,
        smsTempDetail: {},
        isEditOrAddTemp: ''
      }
    },
    components: {
      affix,
      Pagination
    },
    methods: {
      handleCurrentChange (val) {
        this.currentPage = val
        this.fetchData()
      },
      fetchData () {
        let data = {}
        data.account = this.$store.state.session.account.account
        data.page = this.currentPage
        data.limit = this.limit
        let p1 = this.$store.dispatch('queryFlashSmsExamine', data)
        let p2 = this.$store.dispatch('queryShanxinSign', {account: this.$store.state.session.account.account})
        Promise.all([p1, p2]).then(([res, signs]) => {
          this.shanSigns = signs.list
          let tableData = res.list
          this.count = res.count
          tableData.forEach(item => {
            this.flashSmsStatuss.forEach(one => {
              if (item.status === one.codeValue) {
                item.statusName = one.codeName
              }
            })
            this.shanSigns.forEach(one => {
              if (item.sign === one._id) {
                if (one.name[0] === '[' && one.name[one.name.length - 1] === ']') {
                  item.signCon = one.name.substring(1, one.name.length - 1)
                }
              }
            })
          })
          this.tableData = tableData
        })
      },
//      报备闪信mb
      smsTempEditShow () {
        this.isEditOrAddTemp = 'addNewTempState'
        this.isSmsTempEditShow = true
      },
//      报备闪信mb 表格中 点击编辑
      smsTempEditShowFromTable (index, rows) {
        this.isEditOrAddTemp = 'editTempState'
        let data = rows[index]
        this.ruleFormBaoBei.name = data.name
        this.ruleFormBaoBei.content = data.content
        this.ruleFormBaoBei.sign = data.signCon
        this.ruleFormBaoBei._id = data._id
        this.isSmsTempEditShow = true
      },
//      关闭报备模板窗口 清空数据
      closeSmsTempEdit () {
        this.isSmsTempEditShow = false
        for (let i in this.ruleFormBaoBei) {
          this.ruleFormBaoBei[i] = ''
        }
        this.isShowTextCount = false
      },
//      点击dialog外部关闭时 清除数据
      editTempDialogClose () {
        this.closeSmsTempEdit()
      },
//      提交 编辑闪信模板
      postSmsTemplate () {
        let data = {}
        data.name = this.ruleFormBaoBei.name
        data.content = this.ruleFormBaoBei.content
        data.sign = this.ruleFormBaoBei.sign
        data.account = this.$store.state.session.account.account
        if (!data.account) {
          return this.$message.error(this.$t('sms.undefindAccount'))
        }
        if (!data.name || data.name.trim() === '') {
          return this.$message.error(this.$t('sms.pleWriteTitle'))
        }
        if (!data.content || data.content.trim() === '') {
          return this.$message.error(this.$t('sms.pleWriteCon'))
        }
        if (!data.sign || data.sign.trim() === '') {
          return this.$message.error(this.$t('sms.pleWriteSign'))
        }
        data = this.dataCorrection(data)
        data.name = this.delSpecialChar(data.name)
        data.content = this.delSpecialChar(data.content)
        data.sign = this.delSpecialChar(data.sign)
        console.log(data)
        if (this.isEditOrAddTemp === 'addNewTempState') {
          this.$store.dispatch('addShanxinTemplete', data).then(response => {
            if (response.success) {
              this.$message.success(this.$t('sms.successAddBaoBeiTemp'))
              this.fetchData()
              this.closeSmsTempEdit()
            } else {
              this.$message.error(this.$t('sms.sorryAddBaoBeiTemp'))
            }
          })
        }
        if (this.isEditOrAddTemp === 'editTempState') {
          data._id = this.ruleFormBaoBei._id
          this.$store.dispatch('updateShaninTemplete', data).then(response => {
            if (response.success) {
              this.$message.success(this.$t('sms.successEditBaoBeiTemp'))
              this.fetchData()
              this.closeSmsTempEdit()
            } else {
              this.$message.error(this.$t('sms.sorryEditBaoBeiTemp'))
            }
          })
        }
      },
//      处理字符串
      dataCorrection (data) {
        data.content = data.content.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\s/g, '').replace(/\[/g, '').replace(/\]/g, '')
        let sign = data.sign
        sign = sign.replace(/[/g, '').replace(/]/g, '')
        data.sign = '[' + sign + ']'
        return data
      },
//      将英文引号等转换成中文 去掉特殊字符
      delSpecialChar (content) {
        content = content.replace(/\\'/g, "'")
        content = content.replace(/\\"/g, '"')
        let contentarr = content.split('"')
        let str = ''
        let str2 = ''
        for (var j = 0; j < contentarr.length - 1; j++) {
          str += contentarr[j] + (j % 2 ? '”' : '“')
        }
        str += contentarr[j]
        contentarr = str.split("'")
        for (var m = 0; m < contentarr.length - 1; m++) {
          str2 += contentarr[m] + (m % 2 ? '’' : '‘')
        }
        str2 += contentarr[m]
        let reg1 = new RegExp('<[^<]*>', 'gi')
        str2 = str2.replace(reg1, '')
        let reg2 = new RegExp('</', 'gi')
        str2 = str2.replace(reg2, '')
        if (str2.substr(str2.length - 1, 1) === '\\' && str2.substr(str2.length - 2, 2) !== '\\\\') {
          str2 = str2 + '\\'
        }
        return str2
      },
//      编辑模板  input change 计算输入字数
      editTempChange (event) {
        this.isShowTextCount = true
        this.ruleFormBaoBei.content = this.ruleFormBaoBei.content.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\s/g, '').replace(/\[/g, '').replace(/\]/g, '')
        let brackets = this.ruleFormBaoBei.content.match(/{\d+?}/g)
        let bracketsLen = 0
        if (brackets) {
          for (let i = 0; i < brackets.length; i++) {
            bracketsLen += brackets[i].length
          }
        }
        let difference = this.textCount - 2 - this.ruleFormBaoBei.content.length + bracketsLen - this.ruleFormBaoBei.sign.length
        if (difference <= 0) {
          if (event.target.name === 'content') {
            this.ruleFormBaoBei.content = this.ruleFormBaoBei.content.substring(0, this.textCount - 2 - this.ruleFormBaoBei.sign.length + bracketsLen)
          } else {
            this.ruleFormBaoBei.sign = this.ruleFormBaoBei.sign.substring(0, this.textCount - 2 - this.ruleFormBaoBei.content.length + bracketsLen)
          }
          difference = 0
        }
        this.difference = difference
      },
//      删除闪信模板
      delSmsTempFromTable (index, rows) {
        this.$confirm(this.$t('configLazyLoad.sms.sureDelete'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          let dataId = rows[index]._id
          this.$store.dispatch('deleteShanxinTemplete', {_id: dataId}).then(req => {
            if (req.success) {
              this.fetchData()
              this.$message.success(this.$t('sms.successDel'))
            } else {
              this.$message.error(this.$t('sms.failDel'))
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('sms.cancelDel')
          })
        })
      },
//      停用闪信模板
      stopUseSmsTemplateToCheck (index, rows) {
        let data = {}
        data._id = rows[index]._id
        data.status = 'stop'
        this.$store.dispatch('changeShanxinTemplete', data).then(req => {
          if (req.success) {
            this.fetchData()
            this.$message.success(this.$t('sms.stopSuccess'))
          } else {
            this.$message.error(this.$t('sms.stopFail'))
          }
        })
      },
//      启用闪信模板
      reUseSmsTemplateToCheck (index, rows) {
        let data = {}
        data._id = rows[index]._id
        data.status = 'open'
        this.$store.dispatch('changeShanxinTemplete', data).then(req => {
          if (req.success) {
            this.fetchData()
            this.$message.success(this.$t('sms.reuseSuccess'))
          } else {
            this.$message.error(this.$t('sms.reuseFail'))
          }
        })
      },
//      点击 表单中 查看
      showSmsTempDetail (index, rows) {
        let data = {}
        data._id = rows[index]._id
        this.$store.dispatch('getShanxinTempleteById', data).then(response => {
          if (response.success) {
            this.smsTempDetail = response.data
            this.isShowSmsTempDetail = true
          } else {
            this.$message.error(this.$t('sms.searchFail'))
          }
        })
      },
//      关闭查看弹窗
      closeShowSmsTempDetail () {
//        this.cancelSmsTemplateToCheckMessages()
        this.isShowSmsTempDetail = false
      },
      showSmsTempDetailDialogClose () {
        this.closeShowSmsTempDetail()
      }
    },
    beforeMount () {
      let account = this.$store.state.session.account.account
      let p1 = this.$store.dispatch('queryShanxinSign', {account: account})
      let p2 = this.$store.dispatch('getClientDicCache', {type: 'flashSmsStatus'})
      Promise.all([p1, p2]).then(([shanSigns, flashSmsStatus]) => {
        this.shanSigns = shanSigns.list
        this.flashSmsStatuss = flashSmsStatus.data
        this.fetchData()
      })
    },
    activated () {
      this.fetchData()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../../assets/common.styl"
  .span-color
    color $c-pink
  .prompt
    color $c-prompt
    line-height 16px
  .instantSms
    padding 20px
    .tables
      padding 16px 0 0
      .deploy
        height 48px
        line-height 48px
        border 1px solid #ebebeb
        border-bottom none
        padding-left 14px
        .fr
          padding-top 10px
          height 38px
      .red
        color $c-pink !important
      .contentSms
        overflow hidden
        white-space nowrap
        text-overflow ellipsis
        padding-top 6px
        display inline-block
      .item
        margin-right 10px
      .sms-temp-detail-wrap
        word-break break-all
        .sms-temp-detail-con-wrap
          max-height 400px
          overflow-y auto
          .sms-temp-detail-top
            padding 15px 10px
            background-color #fafafa
            border-bottom 1px solid #f3f3f3
            .el-row
              margin-bottom 10px
              .sms-detail-con
                height 90px
                border 1px solid #ccc
                border-radius 6px
                padding 5px
                overflow-y auto
    .ui-affix
      padding-bottom 0
    .bao-bei
      text-align right
    .edit-sms-temp-wrap
      .edit-sms-temp
        overflow hidden
        min-height 370px
        min-width 602px
        .edit-sms-temp-left
          float left
          width 300px
          .edit-sms-temp-line
            margin-bottom 10px
            font-size 12px
            .title-temp
              color $cf-gray1
              margin-right 10px
              display inline-block
            .line-height-x
              float left
              margin-right 14px
            .content-inp
              width 206px
              height 120px
              border 1px solid #ddd
              border-radius 4px
              resize none
            .sign-inp
            .title-inp
              width 202px
              height 24px
              padding 0 4px
              border 1px solid #ddd
              border-radius 2px
            .radio-wrap
              padding 10px 0
            .edit-sms-temp-line-tip
              margin-left 58px
              color $cf-gray3
              .edit-sms-temp-line-special-tip
                color red
        .edit-sms-temp-right
          float right
          width 300px
          height 370px
          background url(../../../../../../assets/img/sms_template_ins.png)
          background-size auto 370px
          background-repeat no-repeat
          position relative
          background-position 60px 0
          .show_sms_tmpl_box
            background-color #41535a
            border-radius 6px
            position absolute
            font-size 12px
            line-height 14px
            color #fff
            left 90px
            top 140px
            width 120px
            word-break break-all
            .top
              padding 3px 0
              text-align center
            .center
              min-height 43px
              padding 4px 6px
            .bottom
              padding 3px 0
              text-align center
              border-top 1px solid #3f4a4c
</style>
